// API 基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL + '/api';

// 获取token
const getToken = () => {
  return localStorage.getItem('admin_token');
};

// 通用请求函数
async function request(url, options = {}) {
  try {
    const headers = {
      'Content-Type': 'application/json',
      ...options.headers,
    };

    // 如果是需要认证的请求，添加token
    const token = getToken();
    if (token && (options.method === 'POST' || options.method === 'PUT' || options.method === 'DELETE')) {
      headers['Authorization'] = `Bearer ${token}`;
    }

    const response = await fetch(`${API_BASE_URL}${url}`, {
      ...options,
      headers,
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error || '请求失败');
    }

    return await response.json();
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
}

// ============ 章节 API ============

export const chapterAPI = {
  // 获取所有章节（admin=true获取所有，否则只获取未隐藏的）
  getAll: (isAdmin = false) => {
    const url = isAdmin ? '/chapters?admin=true' : '/chapters';
    return request(url);
  },

  // 获取单个章节
  getById: (id) => request(`/chapters/${id}`),

  // 创建章节
  create: (data) => request('/chapters', {
    method: 'POST',
    body: JSON.stringify(data),
  }),

  // 更新章节
  update: (id, data) => request(`/chapters/${id}`, {
    method: 'PUT',
    body: JSON.stringify(data),
  }),

  // 删除章节
  delete: (id) => request(`/chapters/${id}`, {
    method: 'DELETE',
  }),
};

// ============ 几何模型 API ============

export const modelAPI = {
  // 获取所有模型（isAdmin=true获取所有，否则只获取未隐藏的）
  getAll: (chapterId, isAdmin = false) => {
    let url = '/models?';
    const params = [];
    if (chapterId) params.push(`chapter_id=${chapterId}`);
    if (isAdmin) params.push('admin=true');
    url += params.join('&');
    return request(url);
  },

  // 获取单个模型
  getById: (id) => request(`/models/${id}`),

  // 创建模型
  create: (data) => request('/models', {
    method: 'POST',
    body: JSON.stringify(data),
  }),

  // 更新模型
  update: (id, data) => request(`/models/${id}`, {
    method: 'PUT',
    body: JSON.stringify(data),
  }),

  // 删除模型
  delete: (id) => request(`/models/${id}`, {
    method: 'DELETE',
  }),

  // 删除特殊模型
  deleteSpecial: (id) => request(`/models/${id}/special`, {
    method: 'DELETE',
  }),

  // 更新特殊模型的模板路径
  updateTemplate: (id, template_path) => request(`/models/${id}/template`, {
    method: 'PUT',
    body: JSON.stringify({ template_path }),
  }),

  // 更新特殊模型的隐藏状态
  updateSpecialHidden: (id, is_hidden) => request(`/models/${id}/hidden`, {
    method: 'PUT',
    body: JSON.stringify({ is_hidden }),
  }),
};

